package ru.ifmo.filemanager.async;

import static ru.ifmo.filemanager.core.Core.error;

import java.util.ArrayDeque;
import java.util.Queue;

class AsyncThread extends Thread {
	
	static final Queue<Runnable> queue = new ArrayDeque<Runnable>();
	static int numThreads, numWaiting;
	
	//Must hold lock on queue
	AsyncThread() {
		super("async");
		++numThreads;
	}

	public void run() {
		while (true) {
			Runnable runnable;
			synchronized (queue) {
				if (queue.isEmpty()) {
					++numWaiting;
					do {
						try {
							queue.wait();
						} catch (InterruptedException e) {
							error("Background thread was interrupted", e, false);
						}
					} while (queue.isEmpty());
					--numWaiting;
				}
				runnable = queue.remove();
			}
			try {
				runnable.run();
			} catch (Throwable e) {
				error("Error in background task", e, false);
			}
		}
	}
}